#include "network/epoll_server.h"
#include "common/logger/logger.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace network;
using namespace common::logger;

// 测试客户端
class TestClient {
public:
    TestClient(const std::string& ip, int port) : ip_(ip), port_(port), sockfd_(-1) {}
    
    ~TestClient() {
        if (sockfd_ >= 0) {
            close(sockfd_);
        }
    }
    
    bool connect() {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0) {
            std::cerr << "创建socket失败: " << strerror(errno) << std::endl;
            return false;
        }
        
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port_);
        inet_pton(AF_INET, ip_.c_str(), &addr.sin_addr);
        
        if (::connect(sockfd_, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
            std::cerr << "连接服务器失败: " << strerror(errno) << std::endl;
            close(sockfd_);
            sockfd_ = -1;
            return false;
        }
        
        std::cout << "连接服务器成功: " << ip_ << ":" << port_ << std::endl;
        return true;
    }
    
    bool send(const std::string& message) {
        if (sockfd_ < 0) {
            std::cerr << "未连接到服务器" << std::endl;
            return false;
        }
        
        ssize_t n = ::send(sockfd_, message.c_str(), message.size(), 0);
        if (n < 0) {
            std::cerr << "发送消息失败: " << strerror(errno) << std::endl;
            return false;
        }
        
        std::cout << "发送消息: " << message << std::endl;
        return true;
    }
    
    std::string receive(int timeout_ms = 5000) {
        if (sockfd_ < 0) {
            std::cerr << "未连接到服务器" << std::endl;
            return "";
        }
        
        // 设置接收超时
        struct timeval tv;
        tv.tv_sec = timeout_ms / 1000;
        tv.tv_usec = (timeout_ms % 1000) * 1000;
        setsockopt(sockfd_, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
        
        char buffer[4096];
        ssize_t n = recv(sockfd_, buffer, sizeof(buffer) - 1, 0);
        
        if (n < 0) {
            if (errno == EAGAIN || errno == EWOULDBLOCK) {
                std::cerr << "接收消息超时" << std::endl;
            } else {
                std::cerr << "接收消息失败: " << strerror(errno) << std::endl;
            }
            return "";
        } else if (n == 0) {
            std::cerr << "服务器关闭连接" << std::endl;
            close(sockfd_);
            sockfd_ = -1;
            return "";
        }
        
        buffer[n] = '\0';
        std::string message(buffer, n);
        std::cout << "接收消息: " << message << std::endl;
        return message;
    }
    
private:
    std::string ip_;
    int port_;
    int sockfd_;
};

// 测试服务器
class TestServer {
public:
    TestServer(int port) : port_(port), server_(nullptr) {}
    
    void start() {
        server_ = std::make_unique<EpollServer>(port_);
        
        server_->setConnectionCallback([](std::shared_ptr<Connection> conn) {
            std::cout << "新连接: " << conn->getIp() << ":" << conn->getPort() << std::endl;
            conn->send("欢迎连接到测试服务器！\n");
        });
        
        server_->setMessageCallback([](std::shared_ptr<Connection> conn, const std::string& message) {
            std::cout << "收到消息: " << message << std::endl;
            std::string response = "服务器回复: " + message;
            conn->send(response);
        });
        
        server_->setCloseCallback([](std::shared_ptr<Connection> conn) {
            std::cout << "连接关闭: " << conn->getIp() << ":" << conn->getPort() << std::endl;
        });
        
        server_->start();
        std::cout << "服务器启动成功，监听端口: " << port_ << std::endl;
    }
    
    void stop() {
        if (server_) {
            server_->stop();
            server_.reset();
        }
        std::cout << "服务器已停止" << std::endl;
    }
    
private:
    int port_;
    std::unique_ptr<EpollServer> server_;
};

// 测试函数
void runTest() {
    // 初始化日志
    Logger::getInstance().setLevel(LogLevel::DEBUG);
    
    // 启动服务器
    TestServer server(8888);
    server.start();
    
    // 等待服务器启动
    std::this_thread::sleep_for(std::chrono::seconds(1));
    
    // 创建客户端
    TestClient client("127.0.0.1", 8888);
    if (!client.connect()) {
        std::cerr << "客户端连接失败" << std::endl;
        server.stop();
        return;
    }
    
    // 接收欢迎消息
    client.receive();
    
    // 发送消息
    client.send("你好，服务器！");
    client.receive();
    
    client.send("测试消息2");
    client.receive();
    
    client.send("测试消息3");
    client.receive();
    
    // 停止服务器
    server.stop();
    
    std::cout << "测试完成" << std::endl;
}

int main() {
    try {
        runTest();
    } catch (const std::exception& e) {
        std::cerr << "测试异常: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
} 